const localSqliteApi = function(DBname = 'main', table_name = 'table1') {
	return {
		// 查询列表
		getList: (params) => new Promise((resolve, reject) => {
			let sql
			if (params) {
				sql = `select * from ${table_name} WHERE `
				Object.keys(params).forEach(function(key) {
					sql = sql + key + '=' + "'" + params[key] + "'" + ' AND'
				})
				sql = sql.substring(0, sql.length - 4); // 去掉最后一个'AND'
			} else {
				sql = `select * from ${table_name}`
			}
			plus.sqlite.selectSql({
				name: DBname,
				sql: sql,
				success: function(data) {
					console.log(`select ${table_name} success: `);
					resolve(data)
					// for (var i in data) {
					// 	console.log(data[i]);
					// }
				},
				fail: function(e) {
					console.log('select table1 failed: ' + JSON.stringify(e));
					reject(e); //失败回调
				}
			})
		}),

		// 查询单一
		getItem: (id) => new Promise((resolve, rejece) => {
			plus.sqlite.selectSql({
				name: DBname,
				sql: `select * from ${table_name} where id=${id}`,
				success: function(data) {
					console.log(`select ${table_name} success: `);
					console.log(data[0])
					resolve(data[0])
				},
				fail: function(e) {
					console.log(`select ${table_name} failed: ` + JSON.stringify(e));
					reject(e); //失败回调
				}
			})
		}),

		// 更新
		update: (params) => new Promise((resolve, reject) => {
			let setFields = ''
			console.log(params["context"])
			Object.keys(params["context"]).forEach(function(key) {
				setFields = "'" + key + "'" + "=" + "'" + params["context"][key] + "'" + ','
			})
			setFields = setFields.substring(0, setFields.length - 1) // 去掉最后一个','
			plus.sqlite.executeSql({
				name: DBname,
				sql: `UPDATE ${table_name} SET ${setFields} WHERE ID = ${params.id};`, // 未完成
				success: function(data) {
					console.log(`${table_name}更新成功`);
					resolve(data)
				},
				fail: function(e) {
					console.log(`update ${table_name} fail`)
					reject(e) // 失败回调
				}
			})
		}),

		// 添加
		insert: (params) => new Promise((resolve, reject) => {
			let fields = ''
			let values = ''
			Object.keys(params).forEach(function(key) {
				fields = fields + key + ',';
				values = values + params[key] + ',';
			})
			fields = fields.substring(0, fields.length - 1) // 去掉最后一个','
			values = values.substring(0, values.length - 1) // 去掉最后一个','
			plus.sqlite.executeSql({
				name: DBname,
				sql: `insert into ${table_name} (${fields}) values ('${values}')`,
				success: function(e) {
					console.log('insert success!');
				},
				fail: function(e) {
					console.log('executeSql failed: ' + JSON.stringify(e));
				}
			});

		})
	}
}

export {
	localSqliteApi
}
